# 1 导入库和设置GPU
# 1.1 导入库
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import matplotlib.pyplot as plt
from datetime import datetime
import warnings

warnings.filterwarnings("ignore")                  # 忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei']    # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False         # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100           # 分辨率

# 1.2 设置GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 2 导入数据
# 2.1 数据下载
train_ds = torchvision.datasets.CIFAR10(
    'data',
    train=True,
    transform=torchvision.transforms.ToTensor(),
    download=True
)

test_ds = torchvision.datasets.CIFAR10(
    'data',
    train=False,
    transform=torchvision.transforms.ToTensor(),
    download=True
)

# 2.2 数据加载
batch_size = 32

train_dl = torch.utils.data.DataLoader(
    train_ds,
    batch_size=batch_size,
    shuffle=True
)

test_dl = torch.utils.data.DataLoader(
    test_ds,
    batch_size=batch_size
)

# 3 构建CNN网络
num_classes = 10

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        # 提取特征网络
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=0)      # 3*32*32  --> 64*30*30
        self.pool1 = nn.MaxPool2d(kernel_size=2)                                                     # 64*30*30 --> 64*15*15
        self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=0)     # 64*15*15 --> 64*13*13
        self.pool2 = nn.MaxPool2d(kernel_size=2)                                                     # 64*13*13 --> 64*6*6
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=0)    # 64*6*6   --> 128*4*4
        self.pool3 = nn.MaxPool2d(kernel_size=2)                                                     # 128*4*4  --> 128*2*2
        # 分类网络
        self.fc1 = nn.Linear(512, 256)                                          # 512 --> 256
        self.fc2 = nn.Linear(256, num_classes)                                             # 256 --> num_classes(10)

    # 前向传播
    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))
        x = self.pool3(F.relu(self.conv3(x)))

        x = torch.flatten(x, start_dim=1)

        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x

# 4 训练模型
# 4.1 设置超参数
model    = Model().to(device)
loss_fn  = nn.CrossEntropyLoss()
opt      = torch.optim.SGD(model.parameters(), lr=1e-2)

# 4.2 编写训练函数
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)   # 训练集大小
    num_batches = len(dataloader)    # 批次数目

    train_loss, train_acc = 0, 0     # 初始化训练损失和正确率

    for X, y in dataloader:
        X, y = X.to(device), y.to(device)

        # 计算预测误差
        pred = model(X)
        loss = loss_fn(pred, y)

        # 反向传播
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # 记录acc和loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc /= size
    train_loss /= num_batches

    return train_acc, train_loss

# 4.3 编写测试函数
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)  # 测试集的大小
    num_batches = len(dataloader)  # 批次数目
    test_loss, test_acc = 0, 0

    # 当不进行训练时，停止梯度更新，节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            # 计算loss
            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss

# 5 正式训练
epochs     = 10
train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%，Test_loss:{:.3f}')
    print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss))

# 6 结果可视化
current_time = datetime.now() # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Test Accuracy')
plt.xlabel(current_time) # 打卡请带上时间戳，否则代码截图无效

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Test Loss')
plt.show()